{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### CNN on MNIST digits classification\n",
    "3-layer CNN for MNIST digits classification\n",
    "- First 2 layers - Conv2D-ReLU-MaxPool\n",
    "- 3rd layer - Conv2D-ReLU-Dropout\n",
    "- 4th layer - Dense(10)\n",
    "- Output Activation - softmax\n",
    "- Optimizer - Adam\n",
    "\n",
    "~99.3% test accuracy in 20epochs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "conv2d_7 (Conv2D)            (None, 26, 26, 64)        640       \n",
      "_________________________________________________________________\n",
      "max_pooling2d_5 (MaxPooling2 (None, 13, 13, 64)        0         \n",
      "_________________________________________________________________\n",
      "conv2d_8 (Conv2D)            (None, 11, 11, 64)        36928     \n",
      "_________________________________________________________________\n",
      "max_pooling2d_6 (MaxPooling2 (None, 5, 5, 64)          0         \n",
      "_________________________________________________________________\n",
      "conv2d_9 (Conv2D)            (None, 3, 3, 64)          36928     \n",
      "_________________________________________________________________\n",
      "flatten_3 (Flatten)          (None, 576)               0         \n",
      "_________________________________________________________________\n",
      "dropout_3 (Dropout)          (None, 576)               0         \n",
      "_________________________________________________________________\n",
      "dense_3 (Dense)              (None, 10)                5770      \n",
      "_________________________________________________________________\n",
      "activation_3 (Activation)    (None, 10)                0         \n",
      "=================================================================\n",
      "Total params: 80,266\n",
      "Trainable params: 80,266\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "Epoch 1/20\n",
      "60000/60000 [==============================] - 87s 1ms/step - loss: 0.2636 - acc: 0.9171\n",
      "Epoch 2/20\n",
      "60000/60000 [==============================] - 96s 2ms/step - loss: 0.0656 - acc: 0.9803\n",
      "Epoch 3/20\n",
      "60000/60000 [==============================] - 125s 2ms/step - loss: 0.0474 - acc: 0.9850\n",
      "Epoch 4/20\n",
      "60000/60000 [==============================] - 125s 2ms/step - loss: 0.0389 - acc: 0.9877\n",
      "Epoch 5/20\n",
      "60000/60000 [==============================] - 125s 2ms/step - loss: 0.0328 - acc: 0.9900\n",
      "Epoch 6/20\n",
      "60000/60000 [==============================] - 128s 2ms/step - loss: 0.0275 - acc: 0.9914\n",
      "Epoch 7/20\n",
      "60000/60000 [==============================] - 132s 2ms/step - loss: 0.0244 - acc: 0.9924\n",
      "Epoch 8/20\n",
      "60000/60000 [==============================] - 123s 2ms/step - loss: 0.0207 - acc: 0.9934\n",
      "Epoch 9/20\n",
      "60000/60000 [==============================] - 132s 2ms/step - loss: 0.0181 - acc: 0.9938\n",
      "Epoch 10/20\n",
      "60000/60000 [==============================] - 136s 2ms/step - loss: 0.0171 - acc: 0.9945\n",
      "Epoch 11/20\n",
      "60000/60000 [==============================] - 130s 2ms/step - loss: 0.0149 - acc: 0.9951\n",
      "Epoch 12/20\n",
      "60000/60000 [==============================] - 104s 2ms/step - loss: 0.0139 - acc: 0.9954\n",
      "Epoch 13/20\n",
      "60000/60000 [==============================] - 77s 1ms/step - loss: 0.0125 - acc: 0.9962\n",
      "Epoch 14/20\n",
      "60000/60000 [==============================] - 80s 1ms/step - loss: 0.0102 - acc: 0.9966\n",
      "Epoch 15/20\n",
      "60000/60000 [==============================] - 85s 1ms/step - loss: 0.0093 - acc: 0.9968\n",
      "Epoch 16/20\n",
      "60000/60000 [==============================] - 93s 2ms/step - loss: 0.0103 - acc: 0.9964\n",
      "Epoch 17/20\n",
      "60000/60000 [==============================] - 86s 1ms/step - loss: 0.0094 - acc: 0.9967\n",
      "Epoch 18/20\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0076 - acc: 0.9973\n",
      "Epoch 19/20\n",
      "60000/60000 [==============================] - 82s 1ms/step - loss: 0.0079 - acc: 0.9974\n",
      "Epoch 20/20\n",
      "60000/60000 [==============================] - 83s 1ms/step - loss: 0.0068 - acc: 0.9977\n",
      "10000/10000 [==============================] - 4s 361us/step\n",
      "\n",
      "Test accuracy: 99.2%\n"
     ]
    }
   ],
   "source": [
    "''' CNN MNIST digits classification\n",
    "'''\n",
    "\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import numpy as np\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Activation, Dense, Dropout\n",
    "from keras.layers import Conv2D, MaxPooling2D, Flatten\n",
    "from keras.utils import to_categorical, plot_model\n",
    "from keras.datasets import mnist\n",
    "\n",
    "# load mnist dataset\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "\n",
    "# compute the number of labels\n",
    "num_labels = len(np.unique(y_train))\n",
    "\n",
    "# convert to one-hot vector\n",
    "y_train = to_categorical(y_train)\n",
    "y_test = to_categorical(y_test)\n",
    "\n",
    "# input image dimensions\n",
    "image_size = x_train.shape[1]\n",
    "# resize and normalize\n",
    "x_train = np.reshape(x_train,[-1, image_size, image_size, 1])\n",
    "x_test = np.reshape(x_test,[-1, image_size, image_size, 1])\n",
    "x_train = x_train.astype('float32') / 255\n",
    "x_test = x_test.astype('float32') / 255\n",
    "\n",
    "# network parameters\n",
    "# image is processed as is (square grayscale)\n",
    "input_shape = (image_size, image_size, 1)\n",
    "batch_size = 128\n",
    "kernel_size = 3\n",
    "pool_size = 2\n",
    "filters = 64\n",
    "dropout = 0.2\n",
    "\n",
    "# model is a stack of CNN-ReLU-MaxPooling\n",
    "model = Sequential()\n",
    "model.add(Conv2D(filters=filters,\n",
    "                 kernel_size=kernel_size,\n",
    "                 activation='relu',\n",
    "                 input_shape=input_shape))\n",
    "model.add(MaxPooling2D(pool_size))\n",
    "model.add(Conv2D(filters=filters,\n",
    "                 kernel_size=kernel_size,\n",
    "                 activation='relu'))\n",
    "model.add(MaxPooling2D(pool_size))\n",
    "model.add(Conv2D(filters=filters,\n",
    "                 kernel_size=kernel_size,\n",
    "                 activation='relu'))\n",
    "model.add(Flatten())\n",
    "# dropout added as regularizer\n",
    "model.add(Dropout(dropout))\n",
    "# output layer is 10-dim one-hot vector\n",
    "model.add(Dense(num_labels))\n",
    "model.add(Activation('softmax'))\n",
    "model.summary()\n",
    "plot_model(model, to_file='cnn-mnist.png', show_shapes=True)\n",
    "\n",
    "# loss function for one-hot vector\n",
    "# use of adam optimizer\n",
    "# accuracy is good metric for classification tasks\n",
    "model.compile(loss='categorical_crossentropy',\n",
    "              optimizer='adam',\n",
    "              metrics=['accuracy'])\n",
    "# train the network\n",
    "model.fit(x_train, y_train, epochs=20, batch_size=batch_size)\n",
    "\n",
    "loss, acc = model.evaluate(x_test, y_test, batch_size=batch_size)\n",
    "print(\"\\nTest accuracy: %.1f%%\" % (100.0 * acc))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
